var nowNum = 0;
window.addEventListener('click', e => {
    // console.log(e)
    if (e.target.attributes.key) {
        let val = e.target.attributes.key.nodeValue;
        displayChange(val, val)
        // console.log(val)

    }
})

function displayChange(type, data) {
    let node = document.querySelector("#display");
    switch (type) {
        case "AC":
            node.innerHTML = "_"
            break;

        case "=":
            let result = caculate(node.innerHTML);
            node.innerHTML = result
            break;

        case "del":
            let oldText = node.innerHTML
            let newText = oldText.substring(0, oldText.length - 1);
            newText = newText == "" ? "_" : newText;
            node.innerHTML = newText
            break;

        default:
            if (node.innerHTML == "_" || node.innerHTML == "ERR" || node.innerHTML == "0") {
                node.innerHTML = data;
            } else {
                node.innerHTML += data;
            }
    }
}
function caculate(data) {
    if (/^[1-9](d*)(\.?)(\d*)(\D{1})[1-9](\d*)(\.?)(\d*)$/.test(data)) {
        let arr = data.match(/[1-9](d*)(\.?)(\d*)/g);
        let num1 = arr[0]
        let num2 = arr[1];
        let operator = data.match(/(\+|-)/);
        operator = operator ? operator[0] : data.match(/(\*|\/)/)[0]
        // console.log(num1, operator, num2)
        switch (operator) {
            case "+":
                return num1 + num2;
                break;

            case "-":
                return num1 - num2;
                break;
            case "*":
                return num1 * num2;
                break;
            case "/":
                return num1 / num2;
                break;
        }
    } else {
        return "ERR"
    }
}